<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 创造者  TODO
 -->

<template>
  <div>
    <van-form class="duck">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.user_name"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell_tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <!-- 选择账号 -->
    <!-- <van-dialog
      v-model="show"
      title="选择接单账号"
      :showCancelButton="true"
      @cancel="onCancel"
      @confirm="onConfirm"
    >
      <van-cell v-for="(account, index) in accountArray" :key="index" center :title="account.no">
        <template #right-icon>
          <van-switch
            v-model="account.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(account, index)"
          />
        </template>
      </van-cell>
    </van-dialog> -->

    <!-- 选择账号 -->
    <van-dialog v-model="show" title="选择接单账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(list, index) in accountArray" :key="index" center :title="list.no">
        <template #right-icon>
          <van-switch
            v-model="list.checked"
            active-color="#e4393c"
            size="24"
            @change="onChange(list, index)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import * as creator from "@/api/creator";
import md5 from "js-md5";
export default {
  name: "Creator",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        user_name: "",
        password: ""
      },
      // 循环时间
      IntervalTime: 5,
      // 任务类型
      type: "0",
      typeOptions: [
        { label: "流量任务", type: "0" },
        { label: "垫付任务", type: "2" }
      ],
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 任务ID
      taskId: "",
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      // 请求头
      headers: "",
      show: false,
      nickRegex: /<div class="item-title">(.+?)<\/div>/g,
      tbIdRegex: /bind_id=(.+?) style/g,
      accountArray: [],
      accountId: [],
      tb_nick: "",
      tb_id: "",
      fingerprint: "",
      // 已接单标记
      isAcceptSuc: false,
activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 31 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    // 监听提示长度
    returnContent() {
      if (this.item.index === 31) {
        if (this.returnContent.length >= 10) {
          this.returnContent = this.returnContent.filter((item, i) => i < 5);
        }
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 31 && this.index !== '') {
        
        this.activeIndex = this.index;
// 获取保存账号信息
        this.ruleForm.user_name = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.type = this.item.type || "0";
        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 31 && this.index !== '') {
      
      this.activeIndex = this.index;
// 获取保存账号信息
      this.ruleForm.user_name = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.type = this.item.type || "0";
    }
  },
  methods: {
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.headers = "";
        this.returnContent = [];
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 登录参数
        let param = {
          type: "post",
          data: this.ruleForm
        };
        creator.ajaxFun(creator.getLogin, param, res => {
          if (res.code === 0) {
            _this.returnContent.unshift(alertMsg(res.msg));
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.user_name,
              pass: _this.ruleForm.password,
              type: _this.type,
              index: _this.index
            });
            // 获取绑定淘宝号
            let param = {
              type: "get",
              dataType: "text",
              data: ""
            };
            creator.ajaxFun(creator.getBindedAccount, param, res => {
              let respon = res.replace(/\r\n/g, "");
              if (respon.match(_this.nickRegex)) {
                // 选择淘宝账号
                (_this.accountArray = []), (_this.accountId = []);
                respon.match(_this.nickRegex).forEach(item => {
                  let str = item.split('>')[1];
                  _this.accountArray.push({
                    no: str.substr(0, str.length -5),
                    checked: false
                  });
                });
                respon.match(_this.tbIdRegex).forEach(item => {
                  let ids = item.split('"');
                  _this.accountId.push(ids[0].substr(8));
                });
                _this.show = true;
              } else {
                let message =
                  res.indexOf(
                    "亲，您目前已经在派单状态或已经派单成功，请稍后再试。"
                  ) !== -1
                    ? "亲，您目前已经在派单状态或已经派单成功，请稍后再试。"
                    : res.indexOf(
                        "恭喜，系统已派发任务，请到未完成任务中做单"
                      ) !== -1
                    ? "恭喜，系统已派发任务，请到未完成任务中做单"
                    : res.indexOf(
                        "目前暂无可派发的垫付任务，请 5 — 10 分钟后再试。"
                      ) !== -1
                    ? "目前暂无可派发的垫付任务，请 5 — 10 分钟后再试。"
                    : "账号不符合要求";
                _this.startFlag = false;
                _this.$dialog
                  .alert({
                    title: "提示",
                    message: message
                  })
                  .then(() => {});
              }
            });
          } else {
            _this.returnContent.unshift(alertMsg("登录异常"));
            _this.startFlag = false;
          }
        });
      } else {
        this.returnContent.unshift(
          alertMsg(
            "平台停止接单，但是后台仍然在接单，平台无法关闭后台接单，请切勿手动停止接单，已免漏单..."
          )
        );
        clearInterval(_this.timer);
        this.isAcceptSuc = false;
        this.startFlag = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 选择账号
    onChange(account, index) {
      this.tb_nick = account.no;
      this.tb_id = this.accountId[index];
      this.show = !this.show;
      this.onConfirm();
    },
    // 取消接单
    onCancel() {
      this.returnContent = [];
      this.startFlag = false;
    },
    // 确认接单
    onConfirm() {
      const _this = this;
      // _this.fingerprint = new Fingerprint2({ screen_resolution: true }).get();
      _this.returnContent.unshift(
        alertMsg("接单号: " + _this.tb_nick + " 即将开始接单，请等待...")
      );
      let param = {
        type: "post",
        data: {
          app_key: creator.app_key,
          challenge: md5(String(creator.challenge))
        }
      };
      creator.ajaxFun(creator.getCaptcha, param, res => {
        _this.challenge = res.result.challenge;
        setTimeout(() => {
          _this.onGetTaskList(_this);
        }, _this.IntervalTime * 1000);
      });
    },
    // 派单
    onGetTaskList(_this) {
      let param = {
        type: "post",
        data: {
          tb_nick: _this.tb_nick,
          tb_id: _this.tb_id,
          challenge: _this.challenge
        }
      };
      creator.ajaxFun(creator.getTaskList, param, res => {
        if (res.code === 0) {
          _this.onGetUserStatus(_this);
        }
      });
    },
    // 持续查询派单状态
    onGetUserStatus(_this) {
      clearInterval(_this.timer);
      let param = {
        type: "post",
        data: {
          task_type: "DIANFU"
        }
      };
      creator.ajaxFun(creator.getUserStatus, param, res => {
        _this.returnContent.unshift(alertMsg("系统正在派单，请耐心等待"));
        if (res.code === 0) {
          _this.timer = setInterval(() => {
            if (_this.startFlag) {
              _this.onGetUserStatus(_this);
            }
          }, _this.IntervalTime * 1000);
        } else {
          // 接单成功
          _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
          audio();
          _this.isAcceptSuc = true;
          _this.startFlag = false;
          _this.$emit("changeOpened", {
            index: _this.activeIndex,
            status: "已接单",
            startFlag: false,
            content: ['接单成功，请前往做单...']
          })
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>




<div class="navbar">
    <div class="navbar-inner">
        <div class="left sliding">
            <a href="#" class="back link"><i class="back_icon"></i><span>返回</span></a>
        </div>
        <div class="center sliding">
            已绑定的账号        </div>
    </div>
</div>
<div class="pages navbar-through fixed-through">
    <div data-page="binded-list" class="page">
        <div class="page-content">
            <div class="list-block media-list" style="margin-top:0;">
                <ul>
                                            <li class="item-content item-link">
                            <div class="item-media">
                                <img src="//cdn.tbquan88.com/binary/taobao_bind_ok.png">                            </div>
                            <div class="item-inner">
                                <div class="item-title-row">
                                    <div class="item-title">
                                        纸短情长！！                                    </div>
                                                                            <div class="item-after" style="display: none;">
                                            <span class="tieyu-back-blue tieyu-max-font tieyu-icon-radius unbind-account"><a href="//www.tbquan88.com/1/pages/bind_huabei?bind_id=2533840" style="color:white;">绑定花呗</a></span>
                                        </div>
                                                                                                                                                    <div class="item-after" style="display: none;">
                                            <span class="tieyu-back-red tieyu-max-font tieyu-icon-radius unbind-account"><a href="//www.tbquan88.com/1/pages/change_address?bind_id=2533840" style="color:white;">修改地址</a></span>
                                        </div>
                                                                    </div>
                                                                                                    <div class="item-text" style="height:auto;">
                                        程小宇 13576512235                                        <br>江西宜春高安大城                                    </div>
                                                            </div>
                        </li>
                                            <li class="item-content item-link">
                            <div class="item-media">
                                <img src="//cdn.tbquan88.com/binary/taobao_bind_ok.png">                            </div>
                            <div class="item-inner">
                                <div class="item-title-row">
                                    <div class="item-title">
                                        97冷暖自知                                    </div>
                                                                            <div class="item-after" style="display: none;">
                                            <span class="tieyu-back-blue tieyu-max-font tieyu-icon-radius unbind-account"><a href="//www.tbquan88.com/1/pages/bind_huabei?bind_id=2533872" style="color:white;">绑定花呗</a></span>
                                        </div>
                                                                                                                                                    <div class="item-after" style="display: none;">
                                            <span class="tieyu-back-red tieyu-max-font tieyu-icon-radius unbind-account"><a href="//www.tbquan88.com/1/pages/change_address?bind_id=2533872" style="color:white;">修改地址</a></span>
                                        </div>
                                                                    </div>
                                                                                                    <div class="item-text" style="height:auto;">
                                        程小宇 18206488595                                        <br>江西宜春高安大城镇                                    </div>
                                                            </div>
                        </li>
                                    </ul>
            </div>
            <div style="height:50px;"></div>
        </div>
    </div>
